package com.uzai.console.service.pyq.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.google.common.collect.Lists;
import com.uzai.common.dto.pyq.FeedMedia;
import com.uzai.common.enums.AttachTypeEnum;
import com.uzai.common.enums.DeviceTypeEnum;
import com.uzai.common.enums.PyqJobStatusEnum;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.console.common.UzaiRespVo;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.dto.pyq.llygoods.PyqLlyGoodsJobBatchSendDao;
import com.uzai.console.dto.pyq.llygoods.PyqLlyGoodsJobSendDao;
import com.uzai.console.entity.PyqDevicePlan;
import com.uzai.console.entity.PyqLlyGoods;
import com.uzai.console.entity.PyqJob;
import com.uzai.console.entity.PyqMaterial;
import com.uzai.console.mapper.PyqDevicePlanMapper;
import com.uzai.console.mapper.PyqLlyGoodsMapper;
import com.uzai.console.mapper.PyqJobMapper;
import com.uzai.console.mapper.PyqMaterialMapper;
import com.uzai.console.service.feign.UzaiBusinessFeignService;
import com.uzai.console.service.feign.dto.LlyGoodsPageDto;
import com.uzai.console.service.pyq.PyqLlyGoodsSyncService;
import com.uzai.console.service.pyq.PyqJobDetailService;
import com.uzai.console.service.pyq.PyqJobSyncService;
import com.uzai.console.service.pyq.PyqMaterialService;
import com.uzai.console.vo.pyq.llygoods.PyqLlyGoodsVo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * 发送老林云商品朋友圈异步执行线程
 * @author liuqi
 * @date 2021年08月13日 11:34
 */
@Service
public class PyqLlyGoodsSyncServiceImpl implements PyqLlyGoodsSyncService {

    Logger logger = LoggerFactory.getLogger(PyqLlyGoodsSyncServiceImpl.class);

    @Autowired
    private PyqJobMapper pyqJobMapper;
    @Autowired
    private PyqJobDetailService pyqJobDetailService;
    @Autowired
    private PyqMaterialService pyqMaterialService;
    @Autowired
    private PyqJobSyncService pyqJobSyncService;
    @Autowired
    private PyqLlyGoodsMapper pyqLlyGoodsMapper;
    @Autowired
    private PyqMaterialMapper pyqMaterialMapper;
    @Autowired
    private PyqDevicePlanMapper pyqDevicePlanMapper;
    @Autowired
    private UzaiBusinessFeignService uzaiBusinessFeignService;

    /**
     * 添加老林云商品群发任务
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param
     * @return null
     */
    @Override
    //@Async("taskExecutor")
    public void  batchAddJobSync(PyqLlyGoodsJobBatchSendDao pyqLlyGoodsJobBatchSendDao, List<Long> deviceUniqueIdList, PyqDevicePlan pyqDevicePlan){

        if(deviceUniqueIdList == null || deviceUniqueIdList.size() == 0){
            return;
        }

        Integer now = DateUtil.getNowTime();
        //页面填写的发送时间
        Integer sendTime_page = now + 5*60; //现在时间+5分钟
        //页面填写了发送时间
        if(pyqLlyGoodsJobBatchSendDao.getSendTime() != null ){
            sendTime_page = pyqLlyGoodsJobBatchSendDao.getSendTime();
        }
        Integer timeInterval = 0;
        //间隔时间,页面填写了间隔时间，单位为分钟
        if(pyqLlyGoodsJobBatchSendDao.getTimeInterval() != null){
            timeInterval = pyqLlyGoodsJobBatchSendDao.getTimeInterval() * 60;
        }
        List<Long> idList = pyqLlyGoodsJobBatchSendDao.getIdList();
        if(idList != null && idList.size() > 0){
            for (int i=0; i<idList.size(); i++){
                try{
                    Long id = idList.get(i);
                    //PyqLlyGoods pyqLlyGoods = pyqLlyGoodsMapper.selectById(id);
                    LlyGoodsPageDto llyGoodsPageDto = new LlyGoodsPageDto();
                    llyGoodsPageDto.setId(id);
                    UzaiRespVo<PyqLlyGoodsVo> uzaiRespVo = uzaiBusinessFeignService.goodsSelectById(llyGoodsPageDto);
                    logger.info("---根据id查询老林云微服务接口---para={},result={}",JSONObject.toJSONString(llyGoodsPageDto),JSONObject.toJSONString(uzaiRespVo));
                    if(uzaiRespVo.getCode() != 200 && uzaiRespVo.getData() == null){
                        return;
                    }
                    PyqLlyGoodsVo pyqLlyGoodsVo = uzaiRespVo.getData();

                    if(pyqLlyGoodsVo != null ){
                        //实际发送时间累加间隔时间(第一次不增加)
                        Integer sendTime_data = sendTime_page + timeInterval * i;
                        PyqJob pyqJob = new PyqJob();
                        pyqJob.setId(IdWorker.getId());
                        pyqJob.setMerId(pyqLlyGoodsJobBatchSendDao.getMerId());
                        pyqJob.setDeviceType(pyqDevicePlan.getDeviceType());
                        pyqJob.setStatus(PyqJobStatusEnum.NOSTART.getValue());
                        pyqJob.setType(pyqLlyGoodsJobBatchSendDao.getType());//老林商品链接
                        pyqJob.setSource(0); //手动发送
                        pyqJob.setPlatform(pyqLlyGoodsJobBatchSendDao.getPlatform());
                        pyqJob.setDevicePlanId(pyqLlyGoodsJobBatchSendDao.getDevicePlanId());
                        pyqJob.setItemId(pyqLlyGoodsVo.getLlyid());   //将商品库商品id保存起来
                        pyqJob.setItemHeaderId(pyqLlyGoodsVo.getGoodsHeaderId());
                        pyqJob.setItemTailId(StringUtils.isNotBlank(pyqLlyGoodsVo.getGoodsTailId())?pyqLlyGoodsVo.getGoodsTailId():pyqLlyGoodsVo.getLlyid());
                        pyqJob.setItemUrl(pyqLlyGoodsVo.getItemUrl());
                        pyqJob.setJpkGoodsId(pyqLlyGoodsVo.getId());  //将商品库主键id保存起来
                        pyqJob.setCouponId(null);

                        //封装附件类型
                        int attachType = 2; //默认图文
                        //封装附件对象
                        List<FeedMedia> feedMediaList = new ArrayList<>();
                        //封装视频号信息
                        String videoNumber = null;
                        //封装商品自带朋友圈内容
                        String content_goods = "";
                        //封装商品自带评论
                        String description_goods = "";

                        //附件模类型
                        List<Integer> materialTypeList = pyqLlyGoodsJobBatchSendDao.getMaterialTypeList();
                        if(materialTypeList.containsAll(Lists.newArrayList(2,5))){     //包括所有，优先商品的视频号，没有则发送图文
                            String materialType = Tools.getStr(pyqLlyGoodsVo.getMaterialType());
                            if(materialType.contains("5")){ //有视频号
                                //附件类型
                                attachType = 5;
                                //附件信息
                                String mediaList = pyqLlyGoodsVo.getMediaList();
                                feedMediaList = JSONObject.parseArray(mediaList, FeedMedia.class);
                                //视频号信息
                                videoNumber = Tools.getStr(pyqLlyGoodsVo.getPyqVideoNumber());
                                //朋友圈内容
                                content_goods = Tools.getStr(pyqLlyGoodsVo.getContentVideo());
                                //评论
                                description_goods = Tools.getStr(pyqLlyGoodsVo.getDescriptionVideo());
                            }else{//无视频，只发图文
                                //附件类型
                                attachType = 2;
                                //朋友圈内容
                                content_goods = Tools.getStr(pyqLlyGoodsVo.getContent());
                                //评论
                                description_goods = Tools.getStr(pyqLlyGoodsVo.getDescription());
                                //图片
                                String itempic = Tools.getStr(pyqLlyGoodsVo.getPic());
                                if(StringUtils.isNotBlank(itempic)){
                                    try {
                                        List<String> itempicList = JSONArray.parseArray(itempic, String.class);
                                        if(itempicList != null && itempicList.size() > 0){
                                            for (String item : itempicList){
                                                if(StringUtils.isNotBlank(item)){
                                                    FeedMedia feedMedia = new FeedMedia();
                                                    feedMedia.setMediaType(2);
                                                    feedMedia.setUrl(item);
                                                    feedMediaList.add(feedMedia);
                                                }
                                            }
                                        }
                                    }catch (Exception e){

                                    }
                                }
                            }
                        }else if(materialTypeList.contains(2)){   //只发图文
                            //附件类型
                            attachType = 2;
                            //朋友圈内容
                            content_goods = Tools.getStr(pyqLlyGoodsVo.getContent());
                            //评论
                            description_goods = Tools.getStr(pyqLlyGoodsVo.getDescription());
                            //图片
                            String itempic = Tools.getStr(pyqLlyGoodsVo.getPic());
                            if(StringUtils.isNotBlank(itempic)){
                                try {
                                    List<String> itempicList = JSONArray.parseArray(itempic, String.class);
                                    if(itempicList != null && itempicList.size() > 0){
                                        for (String item : itempicList){
                                            if(StringUtils.isNotBlank(item)){
                                                FeedMedia feedMedia = new FeedMedia();
                                                feedMedia.setMediaType(2);
                                                feedMedia.setUrl(item);
                                                feedMediaList.add(feedMedia);
                                            }
                                        }
                                    }
                                }catch (Exception e){

                                }
                            }
                        }else{//只发视频号
                            //附件类型
                            attachType = 5;
                            //附件信息
                            String mediaList = pyqLlyGoodsVo.getMediaList();
                            feedMediaList = JSONObject.parseArray(mediaList, FeedMedia.class);
                            //视频号信息
                            videoNumber = Tools.getStr(pyqLlyGoodsVo.getPyqVideoNumber());
                            //朋友圈内容
                            content_goods = Tools.getStr(pyqLlyGoodsVo.getContentVideo());
                            //评论
                            description_goods = Tools.getStr(pyqLlyGoodsVo.getDescriptionVideo());
                        }


                        //判断发送附件类型，如果是图文，则需要判断是否添加自定义图片
                        if(attachType == 2){ //图文
                            //自定义图片不为空，则将自定义图片放到末尾
                            if(StringUtils.isNotBlank(pyqLlyGoodsJobBatchSendDao.getCustomImg())){
                                if(feedMediaList.size() > 8){
                                    feedMediaList = feedMediaList.subList(0, 8);
                                }
                                FeedMedia feedMedia = new FeedMedia();
                                feedMedia.setMediaType(2);
                                feedMedia.setUrl(Tools.getStr(pyqLlyGoodsJobBatchSendDao.getCustomImg()));
                                feedMediaList.add(feedMedia);
                            }
                            if(feedMediaList.size() > 9){
                                feedMediaList = feedMediaList.subList(0, 9);
                            }
                        }

                        //新版朋友圈接口新增加字段
                        pyqJob.setAttachType(attachType);
                        pyqJob.setFeedMedia(Tools.getStrNull(JSONObject.toJSONString(feedMediaList)));
                        pyqJob.setVideoNumber(Tools.getStrNull(videoNumber));
                        pyqJob.setImgs(null);  //新版朋友圈接口，img不存放任何东西

                        pyqJob.setCouponVal(0.0);
                        pyqJob.setFinalPrice(0.0);
                        pyqJob.setContentId(pyqLlyGoodsJobBatchSendDao.getContentId());
                        pyqJob.setCommentId(pyqLlyGoodsJobBatchSendDao.getCommentId());
                        pyqJob.setTotalCount(deviceUniqueIdList.size());
                        pyqJob.setCreateTime(now);
                        pyqJob.setUpdateTime(now);
                        pyqJob.setSendTime(sendTime_data);

                        //朋友圈内容
                        String content = Tools.getStr(pyqLlyGoodsJobBatchSendDao.getContent());
                        //朋友圈内容替换变量
                        content = content.replace("[商品标题]",Tools.getStr(pyqLlyGoodsVo.getTitle()))
                                .replace("[文案]",Tools.getStr(content_goods)) //商品的文案
                                .replace("[原价]",String.valueOf(Tools.getDouble(pyqLlyGoodsVo.getOriginalPrice())))
                                .replace("[券后价]",String.valueOf(Tools.getDouble(pyqLlyGoodsVo.getPostCouponPrice())));
                        pyqJob.setContent(content);

                        //评论内容替换变量
                        List<String> commentList = new ArrayList<>();
                        //是否发送商品自带评论 1-开启
                        if(Tools.getInteger(pyqLlyGoodsJobBatchSendDao.getGoodsComment()).intValue() == 1){
                            try{
                                List<String> descriptionList =JSONObject.parseArray(description_goods, String.class);
                                if(descriptionList != null && descriptionList.size() > 0){
                                    for (String demo : descriptionList){
                                        if(StringUtils.isNotBlank(demo)){
                                            commentList.add(demo);
                                        }
                                    }
                                }
                            }catch (Exception e){
                                logger.error("--商品评论转JSON错误--");
                            }
                        }

                        //页面自定义评论
                        String commentContent = Tools.getStr(pyqLlyGoodsJobBatchSendDao.getCommentContent());
                        commentContent = commentContent.replace("[商品标题]",Tools.getStr(pyqLlyGoodsVo.getTitle()))
                                .replace("[文案]",Tools.getStr(content_goods)) //商品的文案
                                .replace("[原价]",String.valueOf(Tools.getDouble(pyqLlyGoodsVo.getOriginalPrice())))
                                .replace("[券后价]",String.valueOf(Tools.getDouble(pyqLlyGoodsVo.getPostCouponPrice())));
                        //追加页面自定义评论
                        List<String> commentContentList =  JSONArray.parseArray(commentContent, String.class);
                        if(commentContentList != null && commentContentList.size() > 0){
                            for(String demo : commentContentList){
                                if(StringUtils.isNotBlank(demo)){
                                    commentList.add(demo);
                                }
                            }
                        }

                        commentList.removeIf(s -> StringUtils.isBlank(s));
                        pyqJob.setCommentContent(JSONObject.toJSONString(commentList));

                        //后台添加发送明细
                        pyqJobSyncService.addJobSync(pyqJob, deviceUniqueIdList, pyqLlyGoodsJobBatchSendDao.getDomain());
                    }
                }catch (Exception e){

                }
            }
        }

    }

    /**
     * 单个老林云商品添加群发任务
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param
     * @return null
     */
    @Override
    public void  addJobSync(PyqLlyGoodsJobSendDao pyqLlyGoodsJobSendDao, List<Long> deviceUniqueIdList, PyqDevicePlan pyqDevicePlan){

        logger.info("发送朋友圈的机器人数：num={}",deviceUniqueIdList.size());

        if(deviceUniqueIdList == null || deviceUniqueIdList.size() == 0){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请选择机器人");
        }

        Long id = pyqLlyGoodsJobSendDao.getId();
        LlyGoodsPageDto llyGoodsPageDto = new LlyGoodsPageDto();
        llyGoodsPageDto.setId(id);
        UzaiRespVo<PyqLlyGoodsVo> uzaiRespVo = uzaiBusinessFeignService.goodsSelectById(llyGoodsPageDto);
        logger.info("---根据id查询老林云微服务接口---para={},result={}",JSONObject.toJSONString(llyGoodsPageDto),JSONObject.toJSONString(uzaiRespVo));
        if(uzaiRespVo.getCode() != 200 && uzaiRespVo.getData() == null){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "该商品不存在");
        }
        PyqLlyGoodsVo pyqLlyGoodsVo = uzaiRespVo.getData();

        Integer now = DateUtil.getNowTime();
        //发送时间
        Integer sendTime = now + 5*60; //现在时间往后5分钟
        //页面填写了发送时间
        if(pyqLlyGoodsJobSendDao.getSendTime() != null ){
            sendTime = pyqLlyGoodsJobSendDao.getSendTime();
        }

        PyqJob pyqJob = new PyqJob();
        pyqJob.setId(IdWorker.getId());
        pyqJob.setMerId(pyqLlyGoodsJobSendDao.getMerId());
        pyqJob.setDeviceType(pyqDevicePlan.getDeviceType());
        pyqJob.setStatus(PyqJobStatusEnum.NOSTART.getValue());
        pyqJob.setType(pyqLlyGoodsJobSendDao.getType());
        pyqJob.setSource(0); //手动发送
        pyqJob.setPlatform(pyqLlyGoodsJobSendDao.getPlatform());
        pyqJob.setDevicePlanId(pyqLlyGoodsJobSendDao.getDevicePlanId());
        pyqJob.setItemId(pyqLlyGoodsVo.getLlyid());

        pyqJob.setItemHeaderId(pyqLlyGoodsVo.getGoodsHeaderId());
        pyqJob.setItemTailId(StringUtils.isNotBlank(pyqLlyGoodsVo.getGoodsTailId())?pyqLlyGoodsVo.getGoodsTailId():pyqLlyGoodsVo.getLlyid());

        pyqJob.setItemUrl(pyqLlyGoodsVo.getItemUrl());
        //精品库的商品id
        pyqJob.setJpkGoodsId(pyqLlyGoodsVo.getId());
        pyqJob.setCouponId(null);
        pyqJob.setItemUrl(pyqLlyGoodsVo.getItemUrl());

        //封装附件类型
        int attachType = 2; //默认图文
        //封装附件对象
        List<FeedMedia> feedMediaList = new ArrayList<>();
        //封装视频号信息
        String videoNumber = null;
        //封装商品自带朋友圈内容
        String content_goods = "";

        //附件模类型
        List<Integer> materialTypeList = pyqLlyGoodsJobSendDao.getMaterialTypeList();
        if(materialTypeList.contains(2)){//只发图文
            //附件类型
            attachType = 2;
            //图片
            List<String> imgList = pyqLlyGoodsJobSendDao.getImgList();
            if(imgList != null && imgList.size() > 9){
                imgList = imgList.subList(0, 9);
            }
            if(imgList != null && imgList.size() > 0){
                for (String item : imgList){
                    if(StringUtils.isNotBlank(item)){
                        FeedMedia feedMedia = new FeedMedia();
                        feedMedia.setMediaType(2);
                        feedMedia.setUrl(item);
                        feedMediaList.add(feedMedia);
                    }
                }
            }
            //朋友圈内容
            content_goods = Tools.getStr(pyqLlyGoodsVo.getContent());

        }else{//只发视频号
            //附件类型
            attachType = 5;
            //附件信息
            String mediaList = pyqLlyGoodsVo.getMediaList();
            feedMediaList = JSONObject.parseArray(mediaList, FeedMedia.class);
            //视频号信息
            videoNumber = Tools.getStr(pyqLlyGoodsVo.getPyqVideoNumber());

            //朋友圈内容
            content_goods = Tools.getStr(pyqLlyGoodsVo.getContentVideo());

        }

        //新版朋友圈接口新增加字段
        pyqJob.setAttachType(attachType);
        pyqJob.setFeedMedia(Tools.getStrNull(JSONObject.toJSONString(feedMediaList)));
        pyqJob.setVideoNumber(Tools.getStrNull(videoNumber));
        pyqJob.setImgs(null);  //新版朋友圈接口，img不存放任何东西


        pyqJob.setCouponVal(null);
        pyqJob.setFinalPrice(null);
        pyqJob.setContentId(pyqLlyGoodsJobSendDao.getContentId());
        pyqJob.setCommentId(pyqLlyGoodsJobSendDao.getCommentId());
        pyqJob.setTotalCount(deviceUniqueIdList.size());
        pyqJob.setCreateTime(now);
        pyqJob.setUpdateTime(now);
        pyqJob.setSendTime(sendTime);

        //朋友圈内容替换变量
        String content = Tools.getStr(pyqLlyGoodsJobSendDao.getContent());
        content = content.replace("[商品标题]",Tools.getStr(pyqLlyGoodsVo.getTitle()))
                .replace("[文案]",Tools.getStr(content_goods)) //商品的文案
                .replace("[原价]",String.valueOf(Tools.getDouble(pyqLlyGoodsVo.getOriginalPrice())))
                .replace("[券后价]",String.valueOf(Tools.getDouble(pyqLlyGoodsVo.getPostCouponPrice())));
        pyqJob.setContent(content);
        //评论内容替换变量
        String commentContent = Tools.getStr(pyqLlyGoodsJobSendDao.getCommentContent());
        commentContent = commentContent.replace("[商品标题]",Tools.getStr(pyqLlyGoodsVo.getTitle()))
                .replace("[文案]",Tools.getStr(content_goods))
                .replace("[原价]",String.valueOf(Tools.getDouble(pyqLlyGoodsVo.getOriginalPrice())))
                .replace("[券后价]",String.valueOf(Tools.getDouble(pyqLlyGoodsVo.getPostCouponPrice())));

        //去空评论
        List<String> commentContentList = JSONObject.parseArray(commentContent, String.class);
        if(commentContentList != null && commentContentList.size() > 0) {
            commentContentList.removeIf(s -> StringUtils.isBlank(s));
            commentContent = JSONObject.toJSONString(commentContentList);
        }
        pyqJob.setCommentContent(commentContent);

        //后台添加发送明细
        pyqJobSyncService.addJobSync(pyqJob, deviceUniqueIdList, pyqLlyGoodsJobSendDao.getDomain());

        //保存为素材
        if(Tools.getInteger(pyqLlyGoodsJobSendDao.getSaveMaterialFlag()).intValue() == 1){ //保存素材
            PyqMaterial pyqMaterial = new PyqMaterial();
            pyqMaterial.setId(IdWorker.getId());
            pyqMaterial.setMerId(pyqJob.getMerId());
            pyqMaterial.setDeviceType(DeviceTypeEnum.DT_PC_WECHAT.getKey());
            pyqMaterial.setType(pyqJob.getType());
            pyqMaterial.setPlatform(pyqJob.getPlatform());
            pyqMaterial.setDevicePlanId(pyqJob.getDevicePlanId());
            pyqMaterial.setItemId(pyqJob.getItemId());
            pyqMaterial.setCouponId(pyqJob.getCouponId());
            pyqMaterial.setCouponVal(pyqJob.getCouponVal());
            pyqMaterial.setFinalPrice(pyqJob.getFinalPrice());
            pyqMaterial.setContentId(pyqJob.getContentId());
            pyqMaterial.setContent(pyqJob.getContent());
            pyqMaterial.setImgs(pyqJob.getImgs());
            pyqMaterial.setCommentId(pyqJob.getCommentId());
            pyqMaterial.setCommentContent(pyqJob.getCommentContent());

            //新版朋友圈接口新增加字段
            pyqMaterial.setAttachType(pyqJob.getAttachType());
            pyqMaterial.setVideoNumber(pyqJob.getVideoNumber());
            pyqMaterial.setFeedMedia(pyqJob.getFeedMedia());
            pyqMaterial.setImgs(null);  //新版朋友圈接口，img不存放任何东西

            pyqMaterial.setCreateTime(now);
            pyqMaterial.setUpdateTime(now);
            pyqMaterialMapper.insert(pyqMaterial);
        }
    }

}
